﻿using Inovout.Cloud.Models;
using Inovout.Serialization;
using Inovout.Services;
using Inovout.Settings;
using System;
using System.Collections.Generic;

namespace Inovout.Cloud.Identity
{
    public class SettingsService : BaseService
    {
        public IdentirySettings Get(Project project)
        {

            ObjectSettings objectSettings = ComponentRegistry.Resolve<ObjectSettingsService>().FindByScopeAndKindType(project, typeof(IdentirySettings));
            IdentirySettings identirySettings = Build(objectSettings);


            return identirySettings ?? new IdentirySettings();
        }

        private IdentirySettings Build(ObjectSettings objectSettings)
        {
            if (objectSettings == null)
            {
                return null;
            }
            else
            {
                //var itmes = objectSettings.ItemsText.Split('&').Aggregate(new Dictionary<string, string>(),
                //    (result, item) =>
                //    {
                //        string[] kv = item.Split('=');
                //        result.Add(kv[0], kv[1]);
                //        return result;
                //    });
                return new IdentirySettings(
                    new BinarySerializer().Deserialize<Dictionary<string, string>>(objectSettings.ItemsContent)
                    );
            }
        }

        public void Save(Project project, IDictionary<string, string> items)
        {
            ObjectSettingsService objectSettingsService = ComponentRegistry.Resolve<ObjectSettingsService>();
            ObjectSettings objectSettings = objectSettingsService.FindByScopeAndKindType(project, typeof(IdentirySettings));
            if (objectSettings == null)
            {
                objectSettings = new ObjectSettings(project,typeof(IdentirySettings));
            }
            objectSettings.Key = new Uri(items[IdentirySettings.SiteUrlKey]).Authority;
            //objectSettings.ItemsText = items.Aggregate(string.Empty, (result, kv) =>
            //   string.IsNullOrEmpty(result) ? (kv.Key + "=" + kv.Value) : (result + "&" + kv.Key + "=" + kv.Value));


            objectSettings.ItemsContent = new BinarySerializer().SerializeToByteArray(items);
            objectSettingsService.Save(objectSettings);
        }

        public IdentirySettings Get(string siteUrl)
        {
            return Get(new Uri(siteUrl));
        }
        public IdentirySettings Get(Uri siteUrl)
        {
            ObjectSettingsService objectSettingsService = ComponentRegistry.Resolve<ObjectSettingsService>();

            return Build(objectSettingsService.FindByKeyAndKindType(siteUrl.Authority, typeof(IdentirySettings)));
        }
    }
}
